/**
 * Description: socket 服务端 - 使用 recv
 * File: server_recv.c |Time: 2021-04-10 08:36
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

#define ERR(msg) do {            \
             perror(msg);        \
             printf("%s:%s:%d\n", __FILE__, __func__, __LINE__); \
             exit(EXIT_FAILURE); \
         }while(0)

#define BUF_SIZE 100

int main(int argc, char *argv[])
{
    if (argc < 3) {
        printf("Usage: %s <ip> <port>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // 使用socket创建文件描述
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    if (sockfd == -1) {
        ERR("socket");
    }

    // 绑定socket参数
    struct sockaddr_in sockaddr;

    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(argv[2]));
    sockaddr.sin_addr.s_addr = inet_addr(argv[1]);
    if ( bind(sockfd, 
                (struct sockaddr *)&sockaddr, 
                sizeof(struct sockaddr)
            ) == -1) 
    {
        perror("bind faild");
        return -1;
    }

    // 启动监听
    if (listen(sockfd, 5) == -1) {
        perror("listen faild");
        return -1;
    }
    
    // 阻塞等待接收
    struct sockaddr_in clientaddr;
    socklen_t c_sock_len;
    int recvfd;
    char buf[BUF_SIZE];

    printf("server ready, waitting for connection...\n");
    recvfd = accept(sockfd, (struct sockaddr *)&clientaddr, &c_sock_len);

    if (recvfd == -1) {
        perror("accept error");
        return -1;
    } else {
        printf("connected success.\n");
    }

    while(1) {
        recv(recvfd, buf, BUF_SIZE, 0);

        printf("[client msg]: %s\n", buf);

        if (strncmp(buf, "bye", 3) == 0) {
            char *bye = "see you.";
            send(sockfd, bye, strlen(bye), 0);
        }

        memset(buf, 0, BUF_SIZE);

        printf("[reply]:");
        fgets(buf, BUF_SIZE, stdin);
        buf[strlen(buf) - 1] = '\0';
        send(recvfd, buf, strlen(buf), 0);

        memset(buf, 0, BUF_SIZE);
    }


    return 0;
}

